package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuSericeImpl implements MenuService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleDao roleDao;
    @Override
    public List<Map<String, Object>> findByRoleId(String username) {
        List<Map<String, Object>> byRoleId = null;
        User user = userDao.findUserByName(username);
        if (user == null) {
            return null;
        }
        //查询roles属性
        Set<Role> roleSet = roleDao.findRolesByUserId(user.getId());
        //查询permissions属性
        if (roleSet != null && roleSet.size()>0) {
            //封装permissions属性
            for (Role role : roleSet) {
                byRoleId = menuDao.findByRoleId(role.getId());
                int a=1;
                byRoleId = findByRoleIdString(byRoleId, a);
            }
        }
        return  byRoleId;
    }

    public List<Map<String,Object>> findByRoleIdString(List<Map<String,Object>> byRoleId,int a){
        a++;
        for (Map<String, Object> map : byRoleId) {
            if (map!=null) {
                Map<String, Object> integerMap = new HashMap<>();
                integerMap.put("like",map.get("id")+"%");
                integerMap.put("id",a);
                Map<String, Object> integerMap1 = new HashMap<>();
                integerMap1.put("like","/" + map.get("id")+"%");
                integerMap1.put("id",a);
                List<Map<String, Object>> list=  menuDao.findByPriority(integerMap);
                List<Map<String, Object>> list1 = menuDao.findByPriority(integerMap1);
                for (Map<String, Object> objectMap : list) {
                    list1.add(objectMap);
                }
                if (list!=null&&list.size()>0) {
                    findByRoleIdString(list,a);
                }
                map.put("children",list1);
            }
        }
        return byRoleId;
    }
}
